

#include "HTTP.h"

#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <windows.h>
#include "wininet.h"


#ifdef WIP
//implementation, hidden away behind an abstraction just to keep the wininet header out the way.
namespace WinINet
{
	class HTTPRequest : public INET::HTTPRequest
	{
	private:
		HINTERNET mhInternet, mhConnection, mhRequest;
		int mState;
	public:
		enum EState
		{
			EIdle,
			EProcessing,
			
			EComplete,

			ECouldNotConnect = 0xffff0000
		};
		
		HTTPRequest()
			: mhConnection(NULL)
			, mhRequest(NULL)
			, mState(EIdle)
		{	}

		void Request(const char* pServerName, const char* pRequest)
		{
			mhInternet = InternetOpenA("tinyrss.exe", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
			
			if(mhInternet)
			{
				mhConnection = InternetConnectA(mhInternet, pServerName, 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
				if(mhConnection)
				{
					LPCSTR types = "text/";
					mhRequest = HttpOpenRequestA(mhConnection, "GET", pRequest, NULL, NULL, &types, 0, NULL);
				}
			}

			InternetCloseHandle(mhInternet);
		}

	};
}
#endif

namespace INET
{
#ifdef WIP
	HTTPRequest* HTTPRequest::Create(const char* pURI)
	{
		
	}

	void HTTPRequest::Destroy(HTTPRequest* pRq)
	{

	}
#endif


	unsigned long HTTPRequest(const char* pServerName, const char* pRequest, char* pOutputBuffer, size_t outputLen)
	{
		unsigned long read = 0;
		HINTERNET hInternet = InternetOpenA("tinyrss.exe", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
		
		if(hInternet)
		{
			HINTERNET hConnection = InternetConnectA(hInternet, pServerName, 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
			if(hConnection)
			{
				LPCSTR types = "text/";
				HINTERNET hRequest = HttpOpenRequestA(hConnection, "GET", pRequest, NULL, NULL, &types, 0, NULL);

				HttpSendRequestA(hRequest, NULL, 0, NULL, 0);

				//try to get the response
				DWORD dwSize=0;
				bool done = false;
				while(InternetQueryDataAvailable(hRequest, &dwSize, 0, 0) && !done)
				{
					unsigned long r = 0;
					if(read + dwSize < outputLen-1)
					{
						InternetReadFile(hRequest, pOutputBuffer+read, dwSize, &r);
						read += r;
					}
					else
					{
						read = 0;
						done = true;
					}

					if(dwSize == 0)
					{
						done = true;
						pOutputBuffer[read] = 0;
					}
				}

				InternetCloseHandle(hRequest);
			}
			InternetCloseHandle(hConnection);
		}

		InternetCloseHandle(hInternet);

		return read;
	}	

}